import { Button, Collapse, Modal, Input, Form, message, Table, Drawer } from 'antd'
const { Panel } = Collapse
import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Axios } from '../../utils'
import { Add } from '../../components/MyIcon'
import MyCard from '../../components/MyCard'

import './index.css'

// 默认显示数据
const data = {
  src: 'https://t9.baidu.com/it/u=287518385,3207897471&fm=218&app=126&size=f242,150&n=0&f=JPEG&fmt=auto?s=1A2256216C8113685C229B940300408D&sec=1669309200&t=1afaf47ed7960ba9129976913e467a14',
  email: 'zjuSEMG03@zju.edu.cn'
}

// 职业详细信息默认数据
const myDrawerData = {
  jobName: '前端开发工程师',
  content: [
    '1、前端开发。具体来说就是负责如网站、app或小程序的前端开发，并能按照预期完成产品的交互功能;',
    '2、要配合UI设计师实现预期的视觉交互效果;',
    '3、配合服务的工程师完成相关应用的开发工作;',
    '4、定期的更新和优化产品，保持产品的生命力和可用性;',
    '5、解决项目在开发过程中遇到的相关问题，比如技术问题，比如业务问题等。'
  ],
  skills: ['1、精通切图、JS效果，并对项目前端架构和网站性能优化有熟练掌握。', '2、熟练掌握Html、CSS、JavaScript等技术。', '3、拥有主流浏览器的适配实践经验，对于产品在不同平台间的兼容问题要能娴熟处理。', '4、精通jquery, bootstrap等主流js库。', '5、拥有良好的编码和文档处理能力。']
}

// 菜单栏默认数据
const myMenu = [
  {
    key: 1,
    curKey: 14,
    title: '已掌握',
    content: []
  },
  {
    key: 2,
    curKey: 22,
    title: '目标方向',
    content: []
  },
  {
    key: 3,
    curKey: 32,
    title: '目标岗位',
    content: [
      {
        title: '前端',
        key: 21
      }
    ]
  }
]

let tmp_title = ''

let tempType = 0

const UserInfo = React.memo(() => {
  const navigate = useNavigate()

  const [modal, contextHolder] = Modal.useModal()
  const [myFrom] = Form.useForm()

  const [drawerTitle, setDrawerTitle] = useState('岗位介绍') // 抽屉标题
  const [drawerData, setDrawerData] = useState('') // 抽屉数据
  const [menuData, setMenuData] = useState(myMenu) // 菜单内容
  const [techData, setTechData] = useState([]) // 技术列表数据
  const [open, setOpen] = useState(false) // 控制抽屉是否打开
  const [info, setInfo] = useState({}) // 用户信息数据
  const [menu, setMenu] = useState(true) // ？？？好像是没有用的？

  useEffect(() => {
    async function initUserInfo() {
      if (!localStorage.getItem('info')) {
        modal.error({
          title: '权限错误!',
          content: '当前用户未登录，请先前往登录界面登录',
          onOk: () => {
            navigate('/center/login')
          }
        })
        return
      }
      const new_info = JSON.parse(localStorage.getItem('info'))
      setInfo(new_info)
      // 获取技术列表
      Axios({ method: 'get', url: '/tech/techList' }).then(
        response => {
          var res = response.data
          res = res.map(item => {
            return { ...item, key: item.tech_id }
          })

          setTechData(res)
        },
        error => {}
      )

      //获取目标方向
      Axios({
        method: 'post',
        url: '/learn/targetName',
        params: {
          user_mail: new_info.email
        }
      }).then(
        response => {
          setMenuData(prev => {
            prev[1].content = response.data.map((item, index) => {
              return { key: index, title: item }
            })
            return [...prev]
          })
        },
        error => {}
      )
      //获取已掌握
      Axios({
        method: 'post',
        url: '/learn/basicName',
        params: {
          user_mail: new_info.email
        }
      }).then(
        response => {
          console.log(response)
          setMenuData(prev => {
            prev[0].content = response.data.map((item, index) => {
              return { key: index, title: item }
            })
            return [...prev]
          })
        },
        error => {}
      )
    }
    initUserInfo()
  }, [])

  const coloums = [
    {
      title: '技术名称',
      dataIndex: 'tech_name',
      width: '40%'
    },
    {
      title: '难度',
      dataIndex: 'tech_level',
      width: '40%'
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '20%',
      render: (_, record) => {
        return (
          <div>
            <a onClick={() => setAddOne(record.tech_id)}>选择 </a>
          </div>
        )
      }
    }
  ]

  const setAddOne = id => {
    if (tmp_title === '目标方向') {
      Axios({
        method: 'post',
        url: '/learn/addOne/',
        params: {
          user_mail: info.email,
          tech_id: id
        }
      }).then(
        response => {
          message.success({
            content: '添加成功',
            duration: 1
          })
        },
        error => {
          message.error({
            content: '添加失败',
            duration: 1
          })
        }
      )
    } else if (tmp_title === '已掌握') {
      Axios({
        method: 'post',
        url: '/learn/addProcess',
        params: {
          user_mail: info.email,
          tech_id: id
        }
      }).then(
        response => {
          message.success({
            content: '添加成功',
            duration: 1
          })
        },
        error => {
          message.error({
            content: '添加失败',
            duration: 1
          })
        }
      )
    }
  }

  // 菜单展示节点内容映射
  // key: 主内容的key，例如3为学习兴趣
  const menuMapping = (key, title) => {
    if (key === 1) {
      return (
        <div className="UserInfo_flex">
          {title}
          <a
            href="https://www.nowcoder.com/?fromPut=ad_baidu_sem_wushuang_niukexiangguan_shouye&plan_id=204741077&unit_id=7179331255&idea_id=65356238218&keyword=pat%E7%89%9B%E5%AE%A2%E7%BD%91&bd_vid=7520185043646757583"
            target="_blank"
            style={{ cursor: 'pointer', fontWeight: '800', fontSize: '8px', color: 'white', padding: '4px 10px', background: '#FF6741', borderRadius: '10px' }}
          >
            自测
          </a>
        </div>
      )
    } else if (key == 2) {
      return (
        <div className="UserInfo_flex">
          {title}
          <svg
            onClick={() => {
              tempType = 1
              showDrawer()
            }}
            width="18"
            height="16"
            viewBox="0 0 18 16"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M12.375 2.375H14.625C15.2473 2.375 15.75 2.87773 15.75 3.5V12.5C15.75 13.1223 15.2473 13.625 14.625 13.625H12.375C11.7527 13.625 11.25 14.1277 11.25 14.75C11.25 15.3723 11.7527 15.875 12.375 15.875H14.625C16.4883 15.875 18 14.3633 18 12.5V3.5C18 1.63672 16.4883 0.125 14.625 0.125H12.375C11.7527 0.125 11.25 0.627734 11.25 1.25C11.25 1.87227 11.7527 2.375 12.375 2.375ZM12.0445 8.79453C12.484 8.35508 12.484 7.64141 12.0445 7.20195L7.54453 2.70195C7.10508 2.2625 6.39141 2.2625 5.95195 2.70195C5.5125 3.14141 5.5125 3.85508 5.95195 4.29453L8.53242 6.875H1.125C0.502734 6.875 0 7.37773 0 8C0 8.62227 0.502734 9.125 1.125 9.125H8.53242L5.95195 11.7055C5.5125 12.1449 5.5125 12.8586 5.95195 13.298C6.39141 13.7375 7.10508 13.7375 7.54453 13.298L12.0445 8.79805V8.79453Z"
              fill="#EBEBEB"
            />
          </svg>
        </div>
      )
    } else if (key === 3) {
      return (
        <div className="UserInfo_flex">
          {title}
          <svg
            onClick={() => {
              tempType = 1
              showDrawer()
            }}
            width="18"
            height="16"
            viewBox="0 0 18 16"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M12.375 2.375H14.625C15.2473 2.375 15.75 2.87773 15.75 3.5V12.5C15.75 13.1223 15.2473 13.625 14.625 13.625H12.375C11.7527 13.625 11.25 14.1277 11.25 14.75C11.25 15.3723 11.7527 15.875 12.375 15.875H14.625C16.4883 15.875 18 14.3633 18 12.5V3.5C18 1.63672 16.4883 0.125 14.625 0.125H12.375C11.7527 0.125 11.25 0.627734 11.25 1.25C11.25 1.87227 11.7527 2.375 12.375 2.375ZM12.0445 8.79453C12.484 8.35508 12.484 7.64141 12.0445 7.20195L7.54453 2.70195C7.10508 2.2625 6.39141 2.2625 5.95195 2.70195C5.5125 3.14141 5.5125 3.85508 5.95195 4.29453L8.53242 6.875H1.125C0.502734 6.875 0 7.37773 0 8C0 8.62227 0.502734 9.125 1.125 9.125H8.53242L5.95195 11.7055C5.5125 12.1449 5.5125 12.8586 5.95195 13.298C6.39141 13.7375 7.10508 13.7375 7.54453 13.298L12.0445 8.79805V8.79453Z"
              fill="#EBEBEB"
            />
          </svg>
        </div>
      )
    }
  }

  const showDrawer = () => {
    // TODO, 在这里发送网络请求获取展示数据，下面的tempType仅供测试使用

    if (tempType === 0) {
      setDrawerTitle('修改密码')
      setDrawerData(
        <Form className="Login" style={{ display: 'block' }} form={myFrom}>
          <Form.Item
            label="旧密码"
            name="oldPassword"
            rules={[
              {
                required: true,
                message: 'Please input your old password!'
              }
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              {
                required: true,
                message: 'Please input your new password!'
              }
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              onClick={() => {
                myFrom
                  .validateFields()
                  .then(res => {
                    const myInfo = JSON.parse(localStorage.getItem('info'))
                    if (myInfo.password === res.oldPassword) {
                      myInfo.password = res.newPassword
                      localStorage.setItem('info', JSON.stringify(myInfo))
                      message.success({ content: '修改成功!', duration: 2 })
                    } else {
                      message.error({ content: '旧密码错误，请重新输入', duration: 2 })
                    }
                  })
                  .catch(err => {})
              }}
            >
              修改密码
            </Button>
          </Form.Item>
        </Form>
      )
    } else {
      setDrawerTitle(myDrawerData?.jobName)
      setDrawerData(
        <>
          {/* <h3 style={{ fontSize: '24px' }}>岗位名称:{myDrawerData?.jobName}</h3> */}
          <h3>工作内容</h3>
          {myDrawerData?.content?.map(item => {
            return <p>{item}</p>
          })}
          <h3>需要具备的技能</h3>
          {myDrawerData?.skills?.map(item => {
            return <p>{item}</p>
          })}
        </>
      )
    }

    setOpen(true)
  }
  const onClose = () => {
    setOpen(false)
  }
  const onClick = item => {
    tmp_title = item.title

    const config = {
      title: item.title,
      content: (
        <div>
          <Table dataSource={techData} columns={coloums} />
        </div>
      ),
      onOk: f => {
        if (item.title === '目标方向') {
          Axios({
            method: 'post',
            url: '/learn/generate',
            params: {
              user_mail: info.email
            }
          }).then(
            response => {
              message.success({
                content: '已生成对应学习路线',
                duration: 1
              })
            },
            error => {
              message.error({
                content: '添加失败',
                duration: 1
              })
            }
          )
        }

        setMenu(!menu)
        f()
      }
    }
    modal.confirm(config)
  }

  return (
    <div className="UserInfo">
      <div>
        <MyCard>
          <div className="UserInfo_cardItem">
            <img src={data.src}></img>
            <div className="UserInfo_email">{info.email}</div>
            <Button
              type="primary"
              className="UserInfo_btn"
              onClick={() => {
                tempType = 0
                showDrawer()
              }}
            >
              修改密码
            </Button>
            <Button
              type="primary"
              onClick={() => {
                navigate('/center/login')
              }}
              className="UserInfo_btn"
              danger
            >
              退出登陆
            </Button>
          </div>
          <div className="UserInfo_email"></div>
        </MyCard>
      </div>
      <div>
        <Collapse defaultActiveKey={[1]}>
          {menuData.map(item => {
            return (
              <Panel header={item.title} key={item.key}>
                <>
                  {item.content.map(it => {
                    return (
                      <div className="subMenuItem" key={it.key}>
                        {menuMapping(item.key, it.title)}
                      </div>
                    )
                  })}
                  <div className="subMenuItem" onClick={() => onClick(item)}>
                    <Add style={{ cursor: 'pointer' }} />
                  </div>
                </>
              </Panel>
            )
          })}
        </Collapse>
      </div>
      {contextHolder}
      <Drawer title={drawerTitle} closable={false} onClose={onClose} open={open}>
        {drawerData}
      </Drawer>
    </div>
  )
})

export default UserInfo
